package com.ydl.shopping.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ydl.shopping.core.entity.LoginUser;
import com.ydl.shopping.domain.TbLoginInfo;
import com.ydl.shopping.domain.TbUser;
import com.ydl.shopping.mapper.TbUserDetailsMapper;
import com.ydl.shopping.mapper.TbUserMapper;
import com.ydl.shopping.service.ITbLoginInfoService;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 自定义逻辑控制认证
 * 根据唯一性的用户名查询登录用户信息和用户角色权限信息
 *
 * @author 林武泰
 */
@Service
public class TbUserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private TbUserMapper userMapper;

    @Resource
    private TbUserDetailsMapper tbUserDetailsMapper;

    @Resource
    private ITbLoginInfoService loginInfoService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 根据用户名查询信息
        QueryWrapper<TbUser> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", username);
        TbUser user = userMapper.selectOne(userQueryWrapper);

        // 2. 判断用户是否存在
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // 3. 登录日志记录
        TbLoginInfo tbLoginInfo = loginInfoService.loginRegister(username);

        // 4. 判断用户状态是否可用
        if (user.getStatus().equals(0)) {
            String message = "账号已停用";
            // 保存登录日志
            tbLoginInfo.setMsg(message);
            loginInfoService.save(tbLoginInfo);
            throw new LockedException(message);
        }

        // 5. 查询权限信息
        Long userId = user.getId();
        List<String> perms;
        if (userId.equals(1L)) {
            perms = tbUserDetailsMapper.queryPermsBySuperAdmin();
        } else {
            perms = tbUserDetailsMapper.queryPermsByUserId(user.getId());
        }

        return new LoginUser(user, tbLoginInfo, perms);
    }
}
